'''
Descripttion: 
Author: Cxy
Date: 2022-08-23 09:50:01
LastEditors: Cxy
LastEditTime: 2022-08-30 13:07:45
FilePath: \ehomes-admind:\giteeBlog\blogServe\face\modelTraining.py
'''
import json
import cv2 as cv
from glob import *
from PIL import Image
import numpy as np
import click
import os


@click.command()
@click.option('--facepath', default='D:/giteeBlog/blogServe/face', help='Home directory of the file')
def executionProcedure(facepath):
    # 模型训练
    def gataTraining(path):
        # 存放人脸特征数据
        face_Data = []
        # 存放人脸对应的姓名
        ids = []
        # 获取文件夹下所有图片路径
        img_All_Data = glob(path + '*.png')
        face_Model = cv.CascadeClassifier(
            facepath + '/model/haarcascade_frontalface_default.xml')
        for img_Item_Path in img_All_Data:
            i = int(os.path.basename(img_Item_Path).split('.')[1])
            # 将图片转为灰度图像，每个像素用8个bit表示，0表示黑，255表示白，其他数字表示不同的灰度。
            gray_Img = Image.open(img_Item_Path).convert('L')
            # 将灰度图像转为数组
            arr_Img = np.array(gray_Img, 'uint8')
            face_Arr_Data = face_Model.detectMultiScale(arr_Img)
            if len(face_Arr_Data) == 0:
                os.remove(img_Item_Path)
                return 0, 0
            for x, y, w, h in face_Arr_Data:
                face_Data.append(arr_Img[y:y+h, x:x+w])
                ids.append(i)
        return face_Data, ids

    face_Data, ids = gataTraining(facepath + '/faceImg/')
    if face_Data == 0:
        print(json.dumps({'code': 400, 'massage': '人脸无效，请重新录入'}), flush=True)
    else:
        # 获取训练对象
        face_Train = cv.face.LBPHFaceRecognizer_create()
        face_Train.train(face_Data, np.array(ids))
        # 保存文件
        face_Train.save(facepath + '/faceModel.yml')
        print(json.dumps({'code': 200, 'massage': '录入成功'}), flush=True)
    # 释放内存
    cv.destroyAllWindows()


# 调取主程序文件传递参数 因使用click模块不能直接拿到参数
if __name__ == '__main__':
    executionProcedure()
